#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：zhcx-service-test 
@File    ：public_dispatch_way.py
@Author  ：关依林
@Date    ：2023/7/6 14:01 
'''
import os
import re
import time
from concurrent.futures import ThreadPoolExecutor

import requests
import json
import datetime

from decimal import Decimal

from common.dir_config import ConfigHandler
from common.setting import ensure_path_sep
from utils.logging_tool.log_control import LogHandler
from utils.logging_tool.logging_control import Logging
from utils.mysqlUtils.db_utils import DB
from utils.mysqlUtils.mongodb_utils import MongoDBLink
from testcases.ProductGrading_Strategy.invoking_interface import *
from utils.readFileUtils.yamlControl import GetYamlData

filePath = ensure_path_sep("\\config\\config.yaml")
def connectMysql(dbName):
    """

    @param dbName:
    @return:
    """
    cursor = DB(filePath, dbName)
    return cursor

def connectMongo(collName):
    """

    @param sql:
    @return:
    """
    uri = "mongodb://reader:Vly07YmbY0kLt80Y?@121.37.240.172:8635,121.37.230.118:8635/test?authSource=admin&replicaSet=replica"
    dbName = "zhcxkj_center_strategy"
    cursor = MongoDBLink(uri, dbName, collName)
    return cursor

def connectMongoTest(collName):
    """

    @param sql:
    @return:
    """
    uri = "mongodb://admin:Zhcx?2021@10.158.158.29:27017/?authSource=admin"
    dbName = "test_zhcxkj_java_center"
    cursor = MongoDBLink(uri, dbName, collName)
    return cursor

def getIncrementSku(startTime, endTime):
    """

    @param startTime:
    @param endTime:
    """
    mysqlCursorProduct = connectMysql(dbName="mysql_db_strategy_base_product")
    sql = f'SELECT sku FROM t_product_incr WHERE update_time BETWEEN "{startTime}" AND "{endTime}"'
    incrementSkuList = mysqlCursorProduct.execute_sql_many_tuple(sql)
    return incrementSkuList

def dictTransitiontuple(IncrementSkuList):
    """

    @param IncrementSkuList:
    @return:
    """
    res = []
    for i in IncrementSkuList:
        res = res.append(i["sku"])
    return tuple(res)

def getStrategyID():
    """

    @param startTime:
    @param endTime:
    """
    mysqlCursorProduct = connectMysql(dbName="mysql_db_strategy_base_strategy")
    sql = f"SELECT id FROM t_strategy WHERE customer_id = 1 AND is_deleted = 0 AND status = 1"
    strategyIDList = mysqlCursorProduct.execute_sql_many(sql)
    return strategyIDList

def getStrategyCondition(conditionSqlSet):
    """

    @param conditionSqlSet:
    @return:
    """
    conditionList = []
    for key, value in conditionSqlSet.items():
        if value != None:
            conditionList.append(key)
    return conditionList


def getIncrementDataList(incrementApiData):
    """

    @param incrementApiData:
    @return:
    """
    incrementDataList = []
    for i in incrementApiData:
        newTuple = (i["sku"], i["fieldType"], i["oldValue"], i["newValue"])
        incrementDataList.append(newTuple)
    return incrementDataList


def getIncrementBaseData(startTime, endTime):
    """

    @param incrementApiData:
    @return:
    """
    mysqlCursorProduct = connectMysql("mysql_db_strategy_base_product")
    incrementDataSql = f"SELECT sku, field_type, old_value, new_value FROM t_product_incr " \
                       f"WHERE update_time BETWEEN '{startTime}' AND '{endTime}';"
    incrementStockpileData = mysqlCursorProduct.execute_sql_many_tuple(incrementDataSql)
    return incrementStockpileData

def getPaginationBaseData(startId, endId, filedType, cursorProduct):
    if len(filedType) > 1:
        filed = ",".join(filedType)
    else:
        filed = filedType[0]
    incrementDataSql = f"SELECT sku, {filed} FROM rb_product " \
                       f"WHERE id BETWEEN {startId} AND {endId} AND customer_id = 1 AND delete_status = 0"
    incrementStockpileData = cursorProduct.execute_sql_many(incrementDataSql)
    return incrementStockpileData


def GetStrategyRule(categoryId):

    cursorListing = connectMysql("Java_centerStrategy")
    messageSql = f"SELECT condition_field, condition_value, unit " \
                 f"FROM t_strategy_condition WHERE strategy_id = {categoryId}"
    strategyMessage = cursorListing.execute_sql_many(messageSql)
    messageList = [x for x in strategyMessage]
    return messageList

def StrategyRulePack(productStrategyRule):
    filedType = []
    filedTypeOther = []
    filedTypeRelation = []
    strategyRuleValue = []
    strategyRuleValueOther = []
    strategyRuleValueRelation = []
    for i in productStrategyRule:
        conditionName = i["condition_field"]
        if conditionName == "sku_category":
            filedTypeOther.append(conditionName)
            strategyRuleValueOther.append(i)
        elif conditionName == "product_state":
            filedType.append(conditionName)
            strategyRuleValue.append(i)
        elif conditionName == "product_property":
            filedType.append(conditionName)
            strategyRuleValue.append(i)
        elif conditionName == "product_activity":
            filedTypeRelation.append("product_vitality_type")
            strategyRuleValueRelation.append(i)
        elif conditionName == "sku_check_time":
            filedTypeRelation.append("check_time")
            strategyRuleValueRelation.append(i)
        elif conditionName == "develop_type":
            filedType.append(conditionName)
            strategyRuleValue.append(i)
        elif conditionName == "has_law_firm_agent":
            filedType.append(conditionName)
            strategyRuleValue.append(i)
        elif conditionName == "product_logistics_attribute":
            filedType.append("with_battery")
            strategyRuleValue.append(i)
        elif conditionName == "sku_type":
            filedType.append("is_group")
            strategyRuleValue.append(i)
        elif conditionName == "plug_relate_type":
            filedType.append(conditionName)
            strategyRuleValue.append(i)
        elif conditionName == "last_buy_price":
            filedType.append(conditionName)
            strategyRuleValue.append(i)
        elif conditionName == "min_sale_num":
            filedType.append(conditionName)
            strategyRuleValue.append(i)
        elif conditionName == "single_length":
            filedType.append("pack_length")
            filedType.append("pack_width")
            filedType.append("pack_height")
            filedType.append("length")
            filedType.append("width")
            filedType.append("height")
            strategyRuleValue.append(i)
        elif conditionName == "sum_length":
            filedType.append("pack_length")
            filedType.append("pack_width")
            filedType.append("pack_height")
            filedType.append("length")
            filedType.append("width")
            filedType.append("height")
            strategyRuleValue.append(i)
        elif conditionName == "pack_weight":
            filedType.append("pack_weight")
            filedType.append("gross_weight")
            strategyRuleValue.append(i)
        elif conditionName == "volume_weight":
            filedType.append("pack_length")
            filedType.append("pack_width")
            filedType.append("pack_height")
            filedType.append("length")
            filedType.append("width")
            filedType.append("height")
            strategyRuleValue.append(i)
        elif conditionName == "toss_rate":
            filedType.append("pack_length")
            filedType.append("pack_width")
            filedType.append("pack_height")
            filedType.append("length")
            filedType.append("width")
            filedType.append("height")
            filedType.append("pack_weight")
            filedType.append("gross_weight")
            strategyRuleValue.append(i)
    return [list(set(filedType)), filedTypeOther,filedTypeRelation], [strategyRuleValue, strategyRuleValueOther, strategyRuleValueRelation]


def scopeInquire(conditionName, skuData, value):

    keys = list(value.keys())
    if len(keys) > 1:
        skuData = list(filter(lambda x: x[conditionName] != None and value[keys[1]] <= x[conditionName] <= value[keys[0]], skuData))
    else:
        if "max" in keys:
            skuData = list(filter(lambda x: x[conditionName] != None and x[conditionName] <= value[keys[0]],skuData))
        else:
            skuData = list(filter(lambda x: x[conditionName] != None and value[keys[1]] <= x[conditionName], skuData))
    return skuData

def scopeInquire2(skuData, value):

    keys = list(value.keys())
    if len(keys) > 1:
        skuData = list(filter(lambda x:
                              value[keys[1]] <= (max(x["pack_length"], x["pack_width"], x["pack_height"])
                              if max(x["pack_length"], x["pack_width"], x["pack_height"]) > 0
                              else max(x["length"], x["width"], x["height"])) <= value[keys[0]], skuData))
    else:
        if "max" in keys:
            skuData = list(filter(lambda x: (max(x["pack_length"], x["pack_width"], x["pack_height"])
                              if max(x["pack_length"], x["pack_width"], x["pack_height"]) > 0
                              else max(x["length"], x["width"], x["height"])) <= value[keys[0]],skuData))
        else:
            skuData = list(filter(lambda x: value[keys[1]] <= (max(x["pack_length"], x["pack_width"], x["pack_height"])
                              if max(x["pack_length"], x["pack_width"], x["pack_height"]) > 0
                              else max(x["length"], x["width"], x["height"])), skuData))
    return skuData

def scopeInquire3(skuData, value):

    keys = list(value.keys())
    if len(keys) > 1:
        skuData = list(filter(lambda x:
                              value[keys[1]] <= (sum([x["pack_length"], x["pack_width"], x["pack_height"]])
                              if sum([x["pack_length"], x["pack_width"], x["pack_height"]]) > 0
                              else sum([x["length"], x["width"], x["height"]])) <= value[keys[0]], skuData))
    else:
        if "max" in keys:
            skuData = list(filter(lambda x: (sum([x["pack_length"], x["pack_width"], x["pack_height"]])
                              if sum([x["pack_length"], x["pack_width"], x["pack_height"]]) > 0
                              else sum([x["length"], x["width"], x["height"]])) <= value[keys[0]],skuData))
        else:
            skuData = list(filter(lambda x: value[keys[1]] <= (sum([x["pack_length"], x["pack_width"], x["pack_height"]])
                              if sum([x["pack_length"], x["pack_width"], x["pack_height"]]) > 0
                              else sum([x["length"], x["width"], x["height"]])), skuData))
    return skuData

def scopeInquire4(skuData, value):

    keys = list(value.keys())
    if len(keys) > 1:
        skuData = list(filter(lambda x:
                              (x["pack_weight"]!= None and x["pack_weight"]!= 0) or (x["gross_weight"]!= None and x["gross_weight"]!= 0)
                              and value[keys[1]] <=
                              (x["pack_weight"] if x["pack_weight"] != None and x["pack_weight"]!= 0 else x["gross_weight"])
                              <= value[keys[0]], skuData))
    else:
        if "max" in keys:
            skuData = list(filter(lambda x:
                                  (x["pack_weight"] != None and x["pack_weight"] != 0) or (x["gross_weight"] != None and x["gross_weight"] != 0)
                                  and (x["pack_weight"] if x["pack_weight"] != None and x["pack_weight"]!= 0 else x["gross_weight"])
                                  <= value[keys[0]],skuData))
        else:
            skuData = list(filter(lambda x:
                                  (x["pack_weight"] != None and x["pack_weight"] != 0)
                                  or (x["gross_weight"] != None and x["gross_weight"] != 0)
                                  and value[keys[1]] <=
                                  (x["pack_weight"] if x["pack_weight"] != None and x["pack_weight"]!= 0 else x["gross_weight"]), skuData))
    return skuData

def scopeInquire6(customParam, skuData, value):

    keys = list(value.keys())
    if len(keys) > 1:
        skuData = list(filter(lambda x:
                              (((x["pack_length"] * x["pack_width"] * x["pack_height"]) > 0)  or ((x["length"] * x["width"] * x["height"]) > 0))
                              and
                              ((x["pack_weight"] is not None and x["pack_weight"] != 0) or (x["gross_weight"] is not None and x["gross_weight"] != 0))
                              and
                              value[keys[1]] <=
                              (x["pack_length"] * x["pack_width"] * x["pack_height"]
                              / customParam
                              / (x["pack_weight"] if x["pack_weight"] is not None and x["pack_weight"] != 0 else x["gross_weight"]))
                              if (x["pack_length"] * x["pack_width"] * x["pack_height"]) > 0
                              else (
                              x["length"] * x["width"] * x["height"]
                              / customParam
                              / x["pack_weight"] if x["pack_weight"] is not None and x["pack_weight"] != 0 else x["gross_weight"]) <= value[keys[0]], skuData))
    else:
        if "max" in keys:
            skuData = list(filter(lambda x:
                              (((x["pack_length"] * x["pack_width"] * x["pack_height"]) > 0) or ((x["length"] * x["width"] * x["height"]) > 0))
                              and
                              ((x["pack_weight"] is not None and x["pack_weight"] != 0) or (x["gross_weight"] is not None and x["gross_weight"] != 0))
                              and
                              (x["pack_length"] * x["pack_width"] * x["pack_height"] / customParam / (x["pack_weight"] if x["pack_weight"] is not None and x["pack_weight"] != 0 else x["gross_weight"]))
                              if (x["pack_length"] * x["pack_width"] * x["pack_height"]) > 0
                              else (x["length"] * x["width"] * x["height"] / customParam / x["pack_weight"] if x["pack_weight"] is not None and x["pack_weight"] != 0 else x["gross_weight"]) <= value[keys[0]], skuData))
        else:
            skuData = list(filter(lambda x:
                              ((x["pack_length"] * x["pack_width"] * x["pack_height"]) > 0 or (x["length"] * x["width"] * x["height"]) > 0)
                              and
                              ((x["pack_weight"] is not None and x["pack_weight"] != 0) or (x["gross_weight"] is not None and x["gross_weight"] != 0))
                              and
                              value[keys[0]] <= (x["pack_length"] * x["pack_width"] * x["pack_height"] / customParam / (x["pack_weight"] if x["pack_weight"] is not None and x["pack_weight"] != 0 else x["gross_weight"]))
                              if (x["pack_length"] * x["pack_width"] * x["pack_height"]) > 0
                              else (x["length"] * x["width"] * x["height"] / customParam / (x["pack_weight"] if x["pack_weight"] is not None and x["pack_weight"] != 0 else x["gross_weight"])), skuData))
    return skuData

def scopeInquire5(customParam, skuData, value):

    keys = list(value.keys())
    # minValue = value[keys[1]]
    # maxValue = value[keys[0]]
    if len(keys) > 1:
        skuData = list(filter(lambda x:
                              (((x["pack_length"] * x["pack_width"] * x["pack_height"]) > 0)  or ((x["length"] * x["width"] * x["height"]) > 0)) and
                              value[keys[1]] <= ((x["pack_length"] * x["pack_width"] * x["pack_height"] / customParam)
                              if (x["pack_length"] * x["pack_width"] * x["pack_height"]) > 0
                              else (x["length"] * x["width"] * x["height"] / customParam)) <= value[keys[0]], skuData))
    else:
        if "max" in keys:
            skuData = list(filter(lambda x:
                              (((x["pack_length"] * x["pack_width"] * x["pack_height"]) > 0)  or ((x["length"] * x["width"] * x["height"]) > 0)) and
                              ((x["pack_length"] * x["pack_width"] * x["pack_height"] / customParam)
                              if (x["pack_length"] * x["pack_width"] * x["pack_height"]) > 0
                              else (x["length"] * x["width"] * x["height"] / customParam)) <= value[keys[0]], skuData))
        else:
            skuData = list(filter(lambda x:
                              (((x["pack_length"] * x["pack_width"] * x["pack_height"]) > 0)  or ((x["length"] * x["width"] * x["height"]) > 0)) and
                              value[keys[1]] <= ((x["pack_length"] * x["pack_width"] * x["pack_height"] / customParam)
                              if (x["pack_length"] * x["pack_width"] * x["pack_height"]) > 0
                              else (x["length"] * x["width"] * x["height"] / customParam)), skuData))
    return skuData

def scopeInquire7(conditionName, skuData, value, isMark=True):
    if isMark:
        skuData = list(filter(lambda x: x[conditionName] in value, skuData))
    else:
        skuData = list(filter(lambda x: x[conditionName] not in value, skuData))
    return skuData

def scopeInquire8(conditionName, skuData, value):
    unit = value["unit"]
    keys = list(value.keys())
    if unit == "天数":
        if len(keys) > 1:
            minimum = (datetime.datetime.now() + datetime.timedelta(days=-(value["max"]))).strftime("%Y-%m-%d")
            maximum = (datetime.datetime.now() + datetime.timedelta(days=-(value["min"]))).strftime("%Y-%m-%d")
            minimum = datetime.datetime.strptime(minimum + ' 00:00:00', '%Y-%m-%d %H:%M:%S')
            maximum = datetime.datetime.strptime(maximum + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
            skuData = list(filter(lambda x: x["check_time"] != None and minimum <= x["check_time"] <= maximum, skuData))
        else:
            if "max" in keys:
                minimum = (datetime.datetime.now() + datetime.timedelta(days=-(value["max"]))).strftime("%Y-%m-%d")
                minimum = datetime.datetime.strptime(minimum + ' 00:00:00', '%Y-%m-%d %H:%M:%S')
                skuData = list(filter(lambda x: x["check_time"] != None and minimum <= x["check_time"], skuData))
            else:
                maximum = (datetime.datetime.now() + datetime.timedelta(days=-(value["min"]))).strftime("%Y-%m-%d")
                maximum = datetime.datetime.strptime(maximum + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
                skuData = list(filter(lambda x: x["check_time"] != None and x["check_time"] <= maximum, skuData))
    elif unit == "日期":
        if len(keys) > 1:
            minimum = datetime.datetime.strptime(value["min"] + ' 00:00:00', '%Y-%m-%d %H:%M:%S')
            maximum = datetime.datetime.strptime(value["max"] + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
            skuData = list(filter(lambda x: x["check_time"] != None and minimum <= x["check_time"] <= maximum, skuData))
        else:
            if "max" in keys:
                maximum = datetime.datetime.strptime(value["max"] + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
                skuData = list(filter(lambda x: x["check_time"] != None and x["check_time"] <= maximum, skuData))
            else:
                minimum = datetime.datetime.strptime(value["min"] + ' 00:00:00', '%Y-%m-%d %H:%M:%S')
                skuData = list(filter(lambda x: x["check_time"] != None and minimum <= x["check_time"], skuData))
    return skuData

def skuCategoryInquire(cursorCategory, skuData):

    sql = f"SELECT sku, category_id " \
          f"FROM t_sku_category_amazon " \
          f"WHERE sku IN %s AND is_deleted = 0 AND customer_id = 1"
    categoryData = cursorCategory.execute_sql_many1(sql,(skuData,))
    return categoryData

def productSaleStatusInquire(cursorProduct, skuData):

    sql = f"SELECT sku ,product_vitality_type " \
          f"FROM rb_product_sales_status " \
          f"WHERE sku IN %s AND customer_id = 1"
    saleStatusData = cursorProduct.execute_sql_many1(sql,(skuData,))
    return saleStatusData

def productCheckTimeInquire(cursorProduct, skuData):

    sql = f"SELECT sku ,check_time " \
          f"FROM rb_product_admin " \
          f"WHERE sku IN %s AND customer_id = 1"
    saleStatusData = cursorProduct.execute_sql_many1(sql,(skuData,))
    return saleStatusData

def GetStrategyResult(categoryId):
    """

    @param comparison:
    @return:
    """
    mongoCursor = connectMongo("t_sku_strategy_relation")
    sql = json.loads('{' + f'"strategy_relation.strategy_id" : {categoryId}' + '}')
    field = {"_id" : 0 , "sku" : 1}
    strategyResult = mongoCursor.selectTuple3(sql, field)
    return strategyResult

def getStrategyResult2(categoryId,OrderSourceId):
    """

    @param comparison:
    @return:
    """
    mongoCursor = connectMongoTest(f"t_strategy_template_amazon_listing_{categoryId}")
    sql = {"source_id":OrderSourceId}
    field = {"_id":0,"source_id": 1,"msku": 1}
    strategyResult = mongoCursor.select2(sql, field)
    strategyResult = [(i["source_id"], i["msku"]) for i in strategyResult]
    return strategyResult

def getStrategyExportResult(categoryId,OrderSourceId):
    """

    @param comparison:
    @return:
    """
    date = "20231214"
    mongoCursor = connectMongoTest(f"t_strategy_amazon_listing_{categoryId}_{date}")
    sql = {"source_id":OrderSourceId}
    field = {"_id":0,"listing_id": 1}
    strategyResult = mongoCursor.select2(sql, field)
    strategyResult = [(i["listing_id"]) for i in strategyResult]
    return strategyResult

def getCouponStrategyResult(categoryId,OrderSourceId):
    """

    @param comparison:
    @return:
    """
    mongoCursor = connectMongoTest(f"t_strategy_template_amazon_listing_{categoryId}")
    sql = {"source_id":OrderSourceId}
    field = {"_id":0,"source_id": 1,"msku": 1}
    strategyResult = mongoCursor.select2(sql, field)
    strategyResult = [i["asin"] for i in strategyResult]
    return strategyResult
def analysisEnumeration(value):
    tup = ()
    if len(value) == 1:
        tup = f"({value[0]})"
    else:
        for i in value:
            tup = tup + (i,)
    return tup


def getStrategySql(condition):
    """

    @param condition:
    @return:
    """
    strategyConfiguration = GetYamlData(file_dir=ConfigHandler.strategy_dir + "strategy_case.yaml").get_yaml_data()
    conditionName = condition["condition_field"]
    conditionValue = condition["condition_value"]["value"]
    for value in conditionValue:
        conditionSql = strategyConfiguration["sql"][conditionName].replace("$enumerate", value)
        # resSku =
    return conditionName

def getMaxMinId():

    mysqlCursorProduct = connectMysql(dbName="mysql_db_strategy_base_product")
    minIdSql = f"SELECT id FROM `test_zhcxkj_center_product`.`rb_product` ORDER BY `id` LIMIT 1"
    maxIdSql = f"SELECT * FROM `test_zhcxkj_center_product`.`rb_product` ORDER BY `id` DESC LIMIT 1"
    minId = mysqlCursorProduct.execute_sql_many(minIdSql)[0]["id"]
    # minId = 3263
    maxId = mysqlCursorProduct.execute_sql_many(maxIdSql)[0]["id"]
    # maxId = 13263
    if (maxId - minId) % 1000 != 0:
        num = ((maxId - minId) // 1000) + 1
    else:
        num = ((maxId - minId) // 1000)
    return minId, maxId, num

def getMinMaxId(cursorProduct):

    minIdSql = f"SELECT id FROM rb_product ORDER BY id ASC  LIMIT 1"
    maxIdSql = f"SELECT id FROM rb_product ORDER BY id DESC LIMIT 1"
    minId = cursorProduct.execute_sql_many(minIdSql)[0]["id"]
    maxId = cursorProduct.execute_sql_many(maxIdSql)[0]["id"]
    return minId, maxId

def getInquireField(conditionNum, conditionName):
    """

    @param conditionNum:
    @param conditionName:
    @return:
    """
    if conditionNum in ["sku_category", "product_activity", "product_logistics_attribute"]:
        condition = eval(conditionName["condition_value"])["value"]
    elif conditionNum in ["single_length","sum_length","volume_weight","toss_rate"]:
        condition = ["pack_length","pack_width","pack_height","length","width","height","pack_weight","gross_weight"]
    elif conditionNum in ["pack_weight"]:
        condition = ["pack_weight", "gross_weight"]
    elif conditionNum in ["sku_check_time"]:
        condition = ["check_time"]
    elif conditionNum in ["sku_type"]:
        condition = ["is_group"]
    else:
        condition = conditionNum
    return condition

def analysisField(condition):
    """

    @param condition:
    """
    if type(condition) == int:
        filed = [condition]
    elif len(condition) == 0 and type(condition) == list:
        filed = condition[0]
    elif type(condition) == str:
        filed = condition
    else:
        filed = ','.join(str(x) for x in condition)

    return filed

def getProductConditionData(filed, startIndex, endIndex, conditionValue, mysqlCursorProduct):

    if conditionValue in ["product_activity"]:
        sql = f"SELECT a.sku FROM rb_product a JOIN rb_product_sales_status b " \
              f"ON a.customer_id = b.customer_id AND a.sku = b.sku " \
              f"WHERE a.customer_id = 1 AND a.delete_status = 0 AND a.online_status IN (0,1) " \
              f"AND b.product_vitality_type IN ({filed})"
    elif conditionValue in ["product_logistics_attribute"]:
        sql = f"SELECT sku,online_status,with_battery FROM rb_product " \
              f"WHERE id>= {startIndex} AND id<= {endIndex} " \
              f"AND customer_id = 1 AND delete_status = 0"
    elif conditionValue not in ["sku_check_time"]:
        sql = f"SELECT sku,online_status,{filed} FROM rb_product " \
              f"WHERE id>= {startIndex} AND id<= {endIndex} " \
              f"AND customer_id = 1 AND delete_status = 0"
    else:
        sql = f"SELECT a.sku,a.online_status,b.{filed} " \
              f"FROM rb_product a JOIN rb_product_admin b " \
              f"ON a.sku = b.sku AND a.customer_id = b.customer_id " \
              f"WHERE a.id>= {startIndex} AND a.id<= {endIndex} " \
              f"AND a.customer_id = 1 AND a.delete_status = 0"
    res = mysqlCursorProduct.execute_sql_many(sql)
    return res

def getCategoryConditionData(filed, conditionValue, mysqlCursorCategory):
    sql = ""
    if conditionValue in ["sku_category"]:
        sql = f"SELECT sku FROM t_sku_category_amazon " \
              f"WHERE category_id IN ({filed}) " \
              f"AND is_deleted = 0 AND customer_id = 1"
    res = mysqlCursorCategory.execute_sql_many(sql)
    return res

def getBasicsData(dbNameCategory,dbNameProduct,conditionName,messageList,matchingSku,errorSku):

    mysqlCursorProduct = connectMysql(dbNameProduct)
    mysqlCursorCategory = connectMysql(dbNameCategory)
    conditionValue = conditionName["condition_field"]
    try:
        pattern = r'"customParam":\s*(\d+)'
        customParam = int(re.search(pattern, str(messageList)).group(1))
    except:
        pass

    condition = getInquireField(conditionValue, conditionName)
    filed = analysisField(condition)

    minNum, maxNum, num = getMaxMinId()
    startIndex, endIndex = minNum, minNum + 1000

    if conditionValue in ["sku_category","product_activity"]:
        if conditionValue in ["sku_category"]:
            res = getCategoryConditionData(filed, conditionValue, mysqlCursorCategory)
            for data in res:
                matchingSku = matchingSku + ((data["sku"],),)
        elif conditionValue in ["product_activity"]:
            res = getProductConditionData(filed, startIndex, endIndex, conditionValue, mysqlCursorProduct)
            for data in res:
                matchingSku = matchingSku + ((data["sku"],),)
    else:
        for i in range(num):
            print("分页：" + str(startIndex) + "-" + str(endIndex))
            res = getProductConditionData(filed, startIndex, endIndex, conditionValue, mysqlCursorProduct)
            if res != None:
                if conditionValue in [
                    "product_state",
                    "product_property",
                    "develop_type",
                    "product_logistics_attribute",
                    "sku_type"
                ]:

                    if conditionValue == "product_logistics_attribute":
                        conditionValue = "with_battery"
                    elif conditionValue == "sku_type":
                        conditionValue = "is_group"

                    value = eval(conditionName["condition_value"])["value"]
                    if type(value) == int:
                        value = [value]
                    for data in res:
                        if data[conditionValue] in value and data["online_status"] != 2:
                            matchingSku = matchingSku + ((data["sku"],),)
                        else:
                            errorSku = errorSku + ((data["sku"],),)

                    conditionValue = conditionName["condition_field"]

                elif conditionValue in ["plug_relate_type"]:
                    value = conditionName["condition_value"]
                    if "true" in value:
                        value = [x for x in range(12)]
                    for data in res:
                        if data[conditionValue] in value and data["online_status"] != 2:
                            matchingSku = matchingSku + ((data["sku"],),)
                        else:
                            errorSku = errorSku + ((data["sku"],),)

                elif conditionValue in ["last_buy_price", "min_sale_num"]:
                    maximum = eval(conditionName["condition_value"])["max"]
                    minimum = eval(conditionName["condition_value"])["min"]
                    for data in res:
                        if minimum <= data[filed] <= maximum and data["online_status"] != 2:
                            matchingSku = matchingSku + ((data["sku"],),)
                        else:
                            errorSku = errorSku + ((data["sku"],),)

                elif conditionValue in ["pack_weight"]:
                    maximum = eval(conditionName["condition_value"])["max"]
                    minimum = eval(conditionName["condition_value"])["min"]
                    for data in res:
                        if data["pack_weight"] > 0 and minimum <= data["pack_weight"] <= maximum and data["online_status"] != 2 or data["pack_weight"] <= 0 and minimum <= data["gross_weight"] <= maximum and data["online_status"] != 2:
                            matchingSku = matchingSku + ((data["sku"],),)
                        else:
                            errorSku = errorSku + ((data["sku"],),)

                elif conditionValue in ["sku_check_time"]:
                    maximum = eval(conditionName["condition_value"])["max"]
                    minimum = eval(conditionName["condition_value"])["min"]
                    unit = messageList[0]["unit"]
                    if unit == "天数":
                        minCheckTime = (datetime.datetime.now() + datetime.timedelta(days=-maximum)).strftime("%Y-%m-%d")
                        maxCheckTime = (datetime.datetime.now() + datetime.timedelta(days=-minimum)).strftime("%Y-%m-%d")
                        for data in res:
                            if minCheckTime <= str(data["check_time"]) <= maxCheckTime and data["online_status"] != 2:
                                matchingSku = matchingSku + ((data["sku"],),)
                            else:
                                errorSku = errorSku + ((data["sku"],),)
                    else:
                        maxCheckTime = maximum
                        minCheckTime = minimum
                        for data in res:
                            a = str(data["check_time"])
                            if minCheckTime <= str(data["check_time"]) <= maxCheckTime and data["online_status"] != 2:
                                matchingSku = matchingSku + ((data["sku"],),)
                            else:
                                errorSku = errorSku + ((data["sku"],),)

                elif conditionValue in ["single_length","sum_length","volume_weight","toss_rate"]:
                    maximum = eval(conditionName["condition_value"])["max"]
                    minimum = eval(conditionName["condition_value"])["min"]
                    for data in res:
                        if data["online_status"] != 2:
                            packMax = 0
                            if conditionValue == "single_length":
                                pack_length, pack_width, pack_height = data["pack_length"],data["pack_width"],data["pack_height"]
                                if pack_length + pack_length + pack_height <= 0:
                                    length, width, height = data["length"],data["width"],data["height"]
                                    packMax = max(length, width, height)
                                else:
                                    packMax = max(pack_length, pack_width, pack_height)

                            elif conditionValue == "sum_length":
                                pack_length, pack_width, pack_height = data["pack_length"], data["pack_width"], data[
                                    "pack_height"]
                                if pack_length + pack_length + pack_height <= 0:
                                    length, width, height = data["length"], data["width"], data["height"]
                                    packMax = length + width + height
                                else:
                                    packMax = pack_length + pack_width + pack_height

                            elif conditionValue == "volume_weight":
                                customParam = eval(conditionName["condition_value"])["customParam"]
                                pack_length, pack_width, pack_height = data["pack_length"], data["pack_width"], data[
                                    "pack_height"]
                                if pack_length + pack_length + pack_height <= 0:
                                    length, width, height = data["length"], data["width"], data["height"]
                                    packMax = length * width * height / customParam
                                else:
                                    packMax = pack_length * pack_width * pack_height / customParam

                            elif conditionValue == "toss_rate":
                                pack_length, pack_width, pack_height ,pack_weight ,gross_weight = data["pack_length"], data["pack_width"], data[
                                    "pack_height"], data["pack_weight"], data["gross_weight"]
                                if pack_weight <= 0 and gross_weight <= 0:
                                    packMax = -1
                                elif pack_weight <= 0:
                                    if pack_length + pack_length + pack_height <= 0:
                                        length, width, height = data["length"], data["width"], data["height"]
                                        packMax = length * width * height / customParam / gross_weight
                                    else:
                                        packMax = pack_length * pack_width * pack_height / customParam / gross_weight
                                else:
                                    if pack_length + pack_length + pack_height <= 0:
                                        length, width, height = data["length"], data["width"], data["height"]
                                        packMax = length * width * height / customParam / pack_weight
                                    else:
                                        try:
                                            packMax = pack_length * pack_width * pack_height / customParam / pack_weight
                                        except ZeroDivisionError:
                                            packMax = -1

                            if minimum <= packMax <= maximum:
                                matchingSku = matchingSku + ((data["sku"],),)
                            else:
                                errorSku = errorSku + ((data["sku"],),)
                        else:
                            errorSku = errorSku + ((data["sku"],),)
                elif conditionValue in ["plug_relate_type"]:
                    messageValue = [i for i in range(12)]
                    a = messageList[0]["condition_value"]
                    if "true" in messageList[0]["condition_value"]:
                        for data in res:
                            if data["plug_relate_type"] in messageValue and data["online_status"] != 2:
                                matchingSku = matchingSku + ((data["sku"],),)
                            else:
                                errorSku = errorSku + ((data["sku"],),)
                    else:
                        for data in res:
                            if data["plug_relate_type"] not in messageValue and data["online_status"] != 2:
                                matchingSku = matchingSku + ((data["sku"],),)
                            else:
                                errorSku = errorSku + ((data["sku"],),)

                else:
                    for data in res:
                        if data[filed] == messageList[0]["condition_value"] and data["online_status"] != 2:
                            matchingSku = matchingSku + tuple(data["sku"])
                        # else:
                        #     errorSku = errorSku + ((data["sku"],),)
            else:
                continue
            startIndex = endIndex + 1
            endIndex += 1000
        # pool.shutdown(True)
    return matchingSku,errorSku


def useLogHandler(abnormalType, information):
    """

    @param abnormalType:
    @return:
    """
    if abnormalType == "INFO":
        ProductStrategyLogInfo = Logging().log(productName="product_strategy", level='INFO').info(information)
        return ProductStrategyLogInfo
    elif abnormalType == "ERROR":
        ProductStrategyLogError = Logging().log(productName="product_strategy", level='ERROR').error(information)
        return ProductStrategyLogError
    elif abnormalType == "WARNING":
        ProductStrategyLogWarning = Logging().log(productName="product_strategy", level='WARNING').warning(information)
        return ProductStrategyLogWarning
    else:
        print("日志类型输入有误...")


def processingLogic(conditionSqlSet, condition, mysqlCursorProduct, mysqlCursorCategory, sku):
    """

    @param conditionSqlSet:
    @param condition:
    @param mysqlCursorProduct:
    @param mysqlCursorCategory:
    @param sku:
    @return:
    """
    conditionName = condition["condition_field"]

    if conditionName in [
        "product_state",
        "product_property",
        "sku_category",
        "product_activity",
        "develop_type",
        "product_logistics_attribute",
        "sku_type"
        "plug_relate_type"
    ]:
        value = eval(condition["condition_value"])["value"]
        productSkuResult = ()
        for enumerate in value:
            conditionSql = conditionSqlSet[conditionName].replace("$enumerate", str(enumerate))
            # 平台分类sku_category 需要在库 zhcxkj_center_category 进行查询
            if conditionName == "sku_category":
                enumerateResult = mysqlCursorCategory.execute_sql_many_tuple(conditionSql)
                productSkuResult = productSkuResult + enumerateResult
            else:
                enumerateResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
                productSkuResult = productSkuResult + enumerateResult
        if sku:
            result = set(sku) & set(productSkuResult)
        else:
            result = productSkuResult

    # sku_check_time 支持"天数" or "日期"进行过滤
    elif conditionName == "sku_check_time":
        maximum = eval(condition["condition_value"])["max"]
        minimum = eval(condition["condition_value"])["min"]
        startTime = (datetime.datetime.now() + datetime.timedelta(days=-int(maximum if maximum is not None else 0))).strftime("%Y-%m-%d")
        endTime = (datetime.datetime.now() + datetime.timedelta(days=-int(minimum if minimum is not None else 0))).strftime("%Y-%m-%d")
        if condition["unit"] == "天数":
            if minimum == None and maximum is True:
                conditionSql = conditionSqlSet["check_time_day"].replace("$enumerate", f"AND b.check_time <= {endTime}")
            elif maximum == None and minimum is True:
                conditionSql = conditionSqlSet["check_time_day"].replace("$enumerate", f"AND b.check_time >= {startTime}")
            else:
                conditionSql = conditionSqlSet["check_time_day"].replace("$enumerate", f"AND b.check_time BETWEEN {startTime} AND {endTime}")
        else:
            if minimum == None and maximum is True:
                conditionSql = conditionSqlSet["sku_check_time"].replace("$enumerate", f"AND b.check_time <= {endTime}")
            elif maximum == None and minimum is True:
                conditionSql = conditionSqlSet["sku_check_time"].replace("$enumerate", f"AND b.check_time >= {startTime}")
            else:
                conditionSql = conditionSqlSet["sku_check_time"].replace("$enumerate", f"AND b.check_time BETWEEN {startTime} AND {endTime}")
        productSkuResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
        if sku:
            result = set(sku) & set(productSkuResult)
        else:
            result = productSkuResult

    # 部分特殊字段通过最值进行过滤
    elif conditionName in [
        "last_buy_price",
        "min_sale_num",
        "pack_weight"
    ]:
        maximum = eval(condition["condition_value"])["max"]
        minimum = eval(condition["condition_value"])["min"]
        conditionSql = conditionSqlSet[conditionName]
        if minimum == None and maximum is True:
            conditionSql = conditionSql.replace("$enumerate", f"AND {conditionName} <= {maximum}")
        elif maximum == None and minimum is True:
            conditionSql = conditionSql.replace("$enumerate", f"AND {conditionName} >= {minimum}")
        else:
            conditionSql = conditionSql.replace("$enumerate", f"AND {conditionName} BETWEEN {minimum} AND {maximum}")
        productSkuResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
        if sku:
            result = set(sku) & set(productSkuResult)
        else:
            result = productSkuResult

    # 除去上述字段都是通过库 test_zhcxkj_center_product 进行过滤
    elif conditionName in [
        "single_length",
        "sum_length",
        "volume_weight",
        "toss_rate"
    ]:
        maximum = eval(condition["condition_value"])["max"]
        minimum = eval(condition["condition_value"])["min"]
        conditionSql = conditionSqlSet[conditionName]
        if minimum == None and maximum is True:
            conditionSql = conditionSql.replace("$enumerate", f"HAVING result <= {maximum}")
        elif maximum == None and minimum is True:
            conditionSql = conditionSql.replace("$enumerate", f"HAVING result >= {minimum}")
        else:
            conditionSql = conditionSql.replace("$enumerate", f"HAVING result BETWEEN {minimum} AND {maximum}")
        productSkuResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
        productSkuResult = tuple([(i[0],) for i in productSkuResult])
        if sku:
            result = set(sku) & set(productSkuResult)
        else:
            result = productSkuResult

    else:
        result = ()

    return result

def processingLogicIncrement(conditionSqlSet, condition, mysqlCursorProduct, mysqlCursorCategory, sku, IncrementSkuList):
    """

    @param conditionSqlSet:
    @param condition:
    @param mysqlCursorProduct:
    @param mysqlCursorCategory:
    @param sku:
    @return:
    """
    conditionName = condition["condition_field"]

    if conditionName in [
        "product_state",
        "product_property",
        "sku_category",
        "product_activity",
        "develop_type",
        "product_logistics_attribute",
        "sku_type"
        # "plug_relate_type"
    ]:
        value = eval(condition["condition_value"])["value"]
        if type(value) == int:
            value =[value]
        productSkuResult = ()
        # 平台分类sku_category 需要在库 zhcxkj_center_category 进行查询
        if conditionName == "sku_category":
            conditionSql = conditionSqlSet[conditionName].replace("$enumerate", ','.join(str(i) for i in value))
            enumerateResult = mysqlCursorCategory.execute_sql_many_tuple(conditionSql)
            productSkuResult = IncrementSkuList & enumerateResult
        else:

            for i in IncrementSkuList:
                print(i[0])
                conditionSql = conditionSqlSet[conditionName].replace("$enumerate", ','.join(str(i) for i in value))
                conditionSql = conditionSql.replace("$sku", str(i[0]))
                enumerateResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
                productSkuResult = productSkuResult + enumerateResult
        if sku:
            result = set(sku) & set(productSkuResult)
        else:
            result = productSkuResult

    elif conditionName == "plug_relate_type":
        value = condition["condition_value"]
        if "true" in value:
            value = [x for x in range(12)]
        productSkuResult = ()
        for i in IncrementSkuList:
            print(i[0])
            conditionSql = conditionSqlSet[conditionName].replace("$enumerate", ','.join(str(i) for i in value))
            conditionSql = conditionSql.replace("$sku", str(i[0]))
            enumerateResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
            productSkuResult = productSkuResult + enumerateResult
        if sku:
            result = set(sku) & set(productSkuResult)
        else:
            result = productSkuResult

    # sku_check_time 支持"天数" or "日期"进行过滤
    elif conditionName == "sku_check_time":
        maximum = eval(condition["condition_value"])["max"]
        minimum = eval(condition["condition_value"])["min"]

        if condition["unit"] == "天数":
            startTime = (datetime.datetime.now() + datetime.timedelta(days=-int(maximum if maximum is not None else 0))).strftime("%Y-%m-%d")
            endTime = (datetime.datetime.now() + datetime.timedelta(days=-int(minimum if minimum is not None else 0))).strftime("%Y-%m-%d")
            if minimum == None and maximum is True:
                conditionSql = conditionSqlSet["check_time_day"].replace("$enumerate", f"AND b.check_time <= {endTime}")
            elif maximum == None and minimum is True:
                conditionSql = conditionSqlSet["check_time_day"].replace("$enumerate", f"AND b.check_time >= {startTime}")
            else:
                conditionSql = conditionSqlSet["check_time_day"].replace("$enumerate", f"AND b.check_time BETWEEN {startTime} AND {endTime}")
        else:
            startTime = minimum
            endTime = maximum
            if minimum == None and maximum is True:
                conditionSql = conditionSqlSet["sku_check_time"].replace("$enumerate", f"AND b.check_time <= {endTime}")
            elif maximum == None and minimum is True:
                conditionSql = conditionSqlSet["sku_check_time"].replace("$enumerate", f"AND b.check_time >= {startTime}")
            else:
                conditionSql = conditionSqlSet["sku_check_time"].replace("$enumerate", f'AND b.check_time BETWEEN "{startTime}" AND "{endTime}"')
            enumerateResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
            if sku:
                result = set(sku) & set(enumerateResult)
            else:
                result = enumerateResult

    # 部分特殊字段通过最值进行过滤
    elif conditionName in [
        "last_buy_price",
        "min_sale_num"

    ]:
        productSkuResult = ()
        maximum = eval(condition["condition_value"])["max"]
        minimum = eval(condition["condition_value"])["min"]
        if minimum == None and maximum is True:
            conditionSql = conditionSqlSet[conditionName].replace("$enumerate", f"AND {conditionName} <= {maximum}")
        elif maximum == None and minimum is True:
            conditionSql = conditionSqlSet[conditionName].replace("$enumerate", f"AND {conditionName} >= {minimum}")
        else:
            for i in IncrementSkuList:
                print(i[0])
                conditionSql = conditionSqlSet[conditionName].replace("$enumerate", f"AND {conditionName} BETWEEN {minimum} AND {maximum}")
                conditionSql = conditionSql.replace("$sku", str(i[0]))
                enumerateResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
                productSkuResult = productSkuResult + enumerateResult
        if sku:
            result = set(sku) & set(productSkuResult)
        else:
            result = productSkuResult

    elif conditionName in [
      "pack_weight"
    ]:
        maximum = eval(condition["condition_value"])["max"]
        minimum = eval(condition["condition_value"])["min"]
        productSkuResult = ()
        if minimum == None and maximum is True:
            conditionSql = conditionSqlSet[conditionName].replace("$enumerate", f" <= {maximum}")
        elif maximum == None and minimum is True:
            conditionSql = conditionSqlSet[conditionName].replace("$enumerate", f" >= {minimum}")
        else:
            for i in IncrementSkuList:
                print(i[0])
                conditionSql = conditionSqlSet[conditionName].replace("$enumerate", f" BETWEEN {minimum} AND {maximum}")
                conditionSql = conditionSql.replace("$sku", str(i[0]))
                enumerateResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
                productSkuResult = productSkuResult + enumerateResult

        if sku:
            result = set(sku) & set(productSkuResult)
        else:
            result = productSkuResult

    # 除去上述字段都是通过库 test_zhcxkj_center_product 进行过滤
    elif conditionName in [
        "single_length",
        "sum_length",
        "volume_weight",
        "toss_rate"
    ]:
        maximum = eval(condition["condition_value"])["max"]
        minimum = eval(condition["condition_value"])["min"]
        productSkuResult = ()
        if minimum == None and maximum is True:
            conditionSql = conditionSqlSet[conditionName].replace("$enumerate", f"HAVING result <= {maximum}")
        elif maximum == None and minimum is True:
            conditionSql = conditionSqlSet[conditionName].replace("$enumerate", f"HAVING result >= {minimum}")
        else:
            for i in IncrementSkuList:
                print(i[0])
                conditionSql = conditionSqlSet[conditionName].replace("$enumerate", f"HAVING result BETWEEN {minimum} AND {maximum}")
                conditionSql = conditionSql.replace("$sku", str(i[0]))
                enumerateResult = mysqlCursorProduct.execute_sql_many(conditionSql)
                for x in enumerateResult:
                    enumerateResult = ((x["sku"],),)
                productSkuResult = productSkuResult + enumerateResult
        if sku:
            result = set(sku) & set(productSkuResult)
        else:
            result = productSkuResult

    else:
        result = ()

    return result

def processingLogicTest(conditionSqlSet, condition, mysqlCursorProduct, mysqlCursorCategory, sku):
    """

    @param conditionSqlSet:
    @param condition:
    @param mysqlCursorProduct:
    @param mysqlCursorCategory:
    @param sku:
    @return:
    """
    conditionName = condition["condition_field"]

    if conditionName in [
        "product_state",
        "product_property",
        "sku_category",
        "product_activity",
        "develop_type",
        "product_logistics_attribute",
        "sku_type",
        "plug_relate_type"
    ]:
        value = condition["condition_value"]
        if "true" not in value and "false" not in value:
            value = eval(value)["value"]
        else:
            value = value.replace("true", "1").replace("false", "0")
            value = str(eval(value)["value"])
        productSkuResult = ()

        if conditionName in ["sku_category"]:
            conditionSql = conditionSqlSet[conditionName].replace("$enumerate", ','.join(str(i) for i in value))
            enumerateResult = mysqlCursorCategory.execute_sql_many_tuple(conditionSql)
            productSkuResult = productSkuResult + enumerateResult
        else:
            if conditionName in ["product_activity"]:
                conditionSql = conditionSqlSet[conditionName].replace("$enumerate", ','.join(str(i) for i in value))
                enumerateResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
                productSkuResult = productSkuResult + enumerateResult
            else:
                minNum, maxNum, num = getMaxMinId()
                startIndex = minNum
                endIndex = minNum + 1000
                for i in range(num):
                    print("分页查询：" + str(startIndex) + "-" + str(endIndex))
                    conditionSql = conditionSqlSet[conditionName].replace("$enumerate", ','.join(str(i) for i in value))
                    conditionSql = conditionSql.replace("$paging", f'id >= {startIndex} AND id <= {endIndex}')
                    startIndex = endIndex + 1
                    endIndex += 1000
                    enumerateResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
                    if enumerateResult != ():
                        productSkuResult = productSkuResult + enumerateResult
                    else:
                        continue
        if sku:
            result = set(sku) & set(productSkuResult)
        else:
            result = productSkuResult

    # sku_check_time 支持"天数" or "日期"进行过滤
    elif conditionName == "sku_check_time":
        maximum = eval(condition["condition_value"])["max"]
        minimum = eval(condition["condition_value"])["min"]
        startTime = (datetime.datetime.now() + datetime.timedelta(days=-int(maximum if maximum is not None else 0))).strftime("%Y-%m-%d")
        endTime = (datetime.datetime.now() + datetime.timedelta(days=-int(minimum if minimum is not None else 0))).strftime("%Y-%m-%d")
        if condition["unit"] == "天数":
            if minimum == None and maximum is True:
                conditionSql = conditionSqlSet["check_time_day"].replace("$enumerate", f"AND b.check_time <= {endTime}")
            elif maximum == None and minimum is True:
                conditionSql = conditionSqlSet["check_time_day"].replace("$enumerate", f"AND b.check_time >= {startTime}")
            else:
                conditionSql = conditionSqlSet["check_time_day"].replace("$enumerate", f"AND b.check_time BETWEEN {startTime} AND {endTime}")
        else:
            if minimum == None and maximum is True:
                conditionSql = conditionSqlSet["sku_check_time"].replace("$enumerate", f"AND b.check_time <= {endTime}")
            elif maximum == None and minimum is True:
                conditionSql = conditionSqlSet["sku_check_time"].replace("$enumerate", f"AND b.check_time >= {startTime}")
            else:
                conditionSql = conditionSqlSet["sku_check_time"].replace("$enumerate", f"AND b.check_time BETWEEN {startTime} AND {endTime}")
        productSkuResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
        if sku:
            result = set(sku) & set(productSkuResult)
        else:
            result = productSkuResult

    # 部分特殊字段通过最值进行过滤
    elif conditionName in [
        "last_buy_price",
        "min_sale_num",
        "pack_weight"
    ]:
        maximum = eval(condition["condition_value"])["max"]
        minimum = eval(condition["condition_value"])["min"]
        conditionSql = conditionSqlSet[conditionName]
        if minimum == None and maximum is True:
            conditionSql = conditionSql.replace("$enumerate", f"AND {conditionName} <= {maximum}")
        elif maximum == None and minimum is True:
            conditionSql = conditionSql.replace("$enumerate", f"AND {conditionName} >= {minimum}")
        else:
            conditionSql = conditionSql.replace("$enumerate", f"AND {conditionName} BETWEEN {minimum} AND {maximum}")
        productSkuResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
        if sku:
            result = set(sku) & set(productSkuResult)
        else:
            result = productSkuResult

    # 除去上述字段都是通过库 test_zhcxkj_center_product 进行过滤
    elif conditionName in [
        "single_length",
        "sum_length",
        "volume_weight",
        "toss_rate"
    ]:
        maximum = eval(condition["condition_value"])["max"]
        minimum = eval(condition["condition_value"])["min"]
        conditionSql = conditionSqlSet[conditionName]
        if minimum == None and maximum is True:
            conditionSql = conditionSql.replace("$enumerate", f"HAVING result <= {maximum}")
        elif maximum == None and minimum is True:
            conditionSql = conditionSql.replace("$enumerate", f"HAVING result >= {minimum}")
        else:
            conditionSql = conditionSql.replace("$enumerate", f"HAVING result BETWEEN {minimum} AND {maximum}")
        productSkuResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
        productSkuResult = tuple([(i[0],) for i in productSkuResult])
        if sku:
            result = set(sku) & set(productSkuResult)
        else:
            result = productSkuResult

    else:
        result = ()

    return result


def processingLogicTesting(conditionSqlSet, condition, mysqlCursorProduct, mysqlCursorCategory, sku):
    """

    @param conditionSqlSet:
    @param condition:
    @param mysqlCursorProduct:
    @param mysqlCursorCategory:
    @param sku:
    @return:
    """
    conditionName = condition["condition_field"]
    basicsData = getBasicsData(conditionName)

    if conditionName in [
        "product_state",
        "product_property",
        "sku_category",
        "product_activity",
        "develop_type",
        "product_logistics_attribute",
        "sku_type",
        "plug_relate_type"
    ]:
        value = condition["condition_value"]
        if "true" not in value and "false" not in value:
            value = eval(value)["value"]
        else:
            value = value.replace("true", "1").replace("false", "0")
            value = str(eval(value)["value"])
        productSkuResult = ()

        if conditionName in ["sku_category"]:
            conditionSql = conditionSqlSet[conditionName].replace("$enumerate", ','.join(str(i) for i in value))
            enumerateResult = mysqlCursorCategory.execute_sql_many_tuple(conditionSql)
            productSkuResult = productSkuResult + enumerateResult
        else:
            if conditionName in ["product_activity"]:
                conditionSql = conditionSqlSet[conditionName].replace("$enumerate", ','.join(str(i) for i in value))
                enumerateResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
                productSkuResult = productSkuResult + enumerateResult
            else:
                minNum, maxNum, num = getMaxMinId()
                startIndex = minNum
                endIndex = minNum + 1000
                for i in range(num):
                    print("分页查询：" + str(startIndex) + "-" + str(endIndex))
                    conditionSql = conditionSqlSet[conditionName].replace("$enumerate", ','.join(str(i) for i in value))
                    conditionSql = conditionSql.replace("$paging", f'id >= {startIndex} AND id <= {endIndex}')
                    startIndex = endIndex + 1
                    endIndex += 1000
                    enumerateResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
                    if enumerateResult != ():
                        productSkuResult = productSkuResult + enumerateResult
                    else:
                        continue
        if sku:
            result = set(sku) & set(productSkuResult)
        else:
            result = productSkuResult

    # sku_check_time 支持"天数" or "日期"进行过滤
    elif conditionName == "sku_check_time":
        maximum = eval(condition["condition_value"])["max"]
        minimum = eval(condition["condition_value"])["min"]
        startTime = (datetime.datetime.now() + datetime.timedelta(days=-int(maximum if maximum is not None else 0))).strftime("%Y-%m-%d")
        endTime = (datetime.datetime.now() + datetime.timedelta(days=-int(minimum if minimum is not None else 0))).strftime("%Y-%m-%d")
        if condition["unit"] == "天数":
            if minimum == None and maximum is True:
                conditionSql = conditionSqlSet["check_time_day"].replace("$enumerate", f"AND b.check_time <= {endTime}")
            elif maximum == None and minimum is True:
                conditionSql = conditionSqlSet["check_time_day"].replace("$enumerate", f"AND b.check_time >= {startTime}")
            else:
                conditionSql = conditionSqlSet["check_time_day"].replace("$enumerate", f"AND b.check_time BETWEEN {startTime} AND {endTime}")
        else:
            if minimum == None and maximum is True:
                conditionSql = conditionSqlSet["sku_check_time"].replace("$enumerate", f"AND b.check_time <= {endTime}")
            elif maximum == None and minimum is True:
                conditionSql = conditionSqlSet["sku_check_time"].replace("$enumerate", f"AND b.check_time >= {startTime}")
            else:
                conditionSql = conditionSqlSet["sku_check_time"].replace("$enumerate", f"AND b.check_time BETWEEN {startTime} AND {endTime}")
        productSkuResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
        if sku:
            result = set(sku) & set(productSkuResult)
        else:
            result = productSkuResult

    # 部分特殊字段通过最值进行过滤
    elif conditionName in [
        "last_buy_price",
        "min_sale_num",
        "pack_weight"
    ]:
        maximum = eval(condition["condition_value"])["max"]
        minimum = eval(condition["condition_value"])["min"]
        conditionSql = conditionSqlSet[conditionName]
        if minimum == None and maximum is True:
            conditionSql = conditionSql.replace("$enumerate", f"AND {conditionName} <= {maximum}")
        elif maximum == None and minimum is True:
            conditionSql = conditionSql.replace("$enumerate", f"AND {conditionName} >= {minimum}")
        else:
            conditionSql = conditionSql.replace("$enumerate", f"AND {conditionName} BETWEEN {minimum} AND {maximum}")
        productSkuResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
        if sku:
            result = set(sku) & set(productSkuResult)
        else:
            result = productSkuResult

    # 除去上述字段都是通过库 test_zhcxkj_center_product 进行过滤
    elif conditionName in [
        "single_length",
        "sum_length",
        "volume_weight",
        "toss_rate"
    ]:
        maximum = eval(condition["condition_value"])["max"]
        minimum = eval(condition["condition_value"])["min"]
        conditionSql = conditionSqlSet[conditionName]
        if minimum == None and maximum is True:
            conditionSql = conditionSql.replace("$enumerate", f"HAVING result <= {maximum}")
        elif maximum == None and minimum is True:
            conditionSql = conditionSql.replace("$enumerate", f"HAVING result >= {minimum}")
        else:
            conditionSql = conditionSql.replace("$enumerate", f"HAVING result BETWEEN {minimum} AND {maximum}")
        productSkuResult = mysqlCursorProduct.execute_sql_many_tuple(conditionSql)
        productSkuResult = tuple([(i[0],) for i in productSkuResult])
        if sku:
            result = set(sku) & set(productSkuResult)
        else:
            result = productSkuResult

    else:
        result = ()

    return result


if __name__ == '__main__':
    useLogHandler(abnormalType=("INFO"), information="111")
